package comm.net.protocol;


import comm.utill.Param;

public class Protocol {

    private Protobuf.Pro.Builder m_pro;
    private Head m_head;
    private Param m_body;

    public Protocol() {
        m_head = new Head();
        m_body = new Param();
        m_pro = Protobuf.Pro.newBuilder();
    }

    public Protocol(Object obj) {
        this();

        if (obj instanceof Protobuf.Pro) {
            Protobuf.Pro pro = (Protobuf.Pro) obj;

            Protobuf.Head head = pro.getHead();
            Protobuf.Body body = pro.getBody();

            // 把头数据设置给head
            m_head.setCmd(head.getCmd());
            m_head.setId(head.getId());

            // 把数据设置给body
            setBody(Param.decodeing(body.getDataMap()));
        }
    }

    public static class Head {
        private int cmd = 0;
        private int id = 0;

        public int getCmd() {
            return cmd;
        }

        public void setCmd(int cmd) {
            this.cmd = cmd;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }


    public int getCmd() {
        return m_head.getCmd();
    }

    public void setCmd(int cmd) {
        m_head.setCmd(cmd);
    }

    public int getId() {
        return m_head.getId();
    }

    public void setId(int id) {
        m_head.setId(id);
    }

    public Param getBody(){
        return m_body;
    }

    public void setBody(Param body){
        m_body = body;
    }

    // 返回协议对象
    public Protobuf.Pro.Builder getPro() {
        Protobuf.Body.Builder sendBody = Protobuf.Body.newBuilder();
        sendBody.putAllData(m_body.encoding());

        Protobuf.Head.Builder sendHead = Protobuf.Head.newBuilder();
        sendHead.setCmd(m_head.getCmd());
        sendHead.setId(m_head.getId());

        m_pro.setBody(sendBody);
        m_pro.setHead(sendHead);
        return m_pro;
    }

    public void setPro(Protobuf.Pro.Builder pro){
        m_pro.setBody(pro.getBody());
        m_pro.setHead(pro.getHead());

        // 把头数据设置给head
        m_head.setCmd(pro.getHead().getCmd());
        m_head.setId(pro.getHead().getId());

        // 把数据设置给body
        setBody(Param.decodeing(pro.getBody().getDataMap()));
    }


}
